package org.wx.herostory.services.handler;

import com.google.protobuf.GeneratedMessageV3;
import com.google.protobuf.Message;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.ReplayingDecoder;
import io.netty.handler.codec.http.websocketx.BinaryWebSocketFrame;
import lombok.extern.slf4j.Slf4j;
import org.wx.herostory.msg.GameMsgProtocol;
import org.wx.herostory.services.decoder.GameMsgRecognizer;

import java.util.List;

/**
 * @description: 消息解码器
 * @author: wangxun
 * @createDate: 2021/3/1
 * @version: 1.0
 */
@Slf4j
public class GameMsgDecoder extends ChannelInboundHandlerAdapter {

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {

        if (ctx == null || msg==null) {
            return;
        }
        if(!(msg instanceof BinaryWebSocketFrame)){
            return;
        }
        BinaryWebSocketFrame frame = (BinaryWebSocketFrame) msg;

        // websocket 的消息体
        ByteBuf content = frame.content();

        // 消息长度
        short contentLength = content.readShort();
        // 消息的编号
        int msgCode = content.readShort();
        // 消息内容
        byte[] contentBytes = new byte[content.readableBytes()];
        content.readBytes(contentBytes);
        log.info("接受到客户端请求，消息长度:{} 消息编号:{} 消息体:{}",contentLength,msgCode,new String(contentBytes));

        Message.Builder msgBuilder = GameMsgRecognizer.getBuilderByMsgCode(msgCode);
        msgBuilder.clear();
        msgBuilder.mergeFrom(contentBytes);
        Message cmd = msgBuilder.build();

        if (null != cmd) {
            ctx.fireChannelRead(cmd);
        }
    }


}
